<template>
  <detail-page :nav_list="nav_list" v-on:change-menu="changeMenu">
    <div class="main" v-if="menuIdx == 0">
      <el-row :gutter="20">
        <el-col :span="14">
          <div>
            <div class="table_title">
              {{ lusHeader.k4093 }}- {{ lusHeader.beginTime }} -
              {{ lusHeader.endTime }}
            </div>
            <div class="flex">
              <div class="table_sub">{{ lusHeader.k4092 }}</div>
              <div class="table_sub">{{ lusHeader.k1002 }}</div>
            </div>
            <el-table
              :data="lusTable"
              max-height="400"
              border
              style="width: 100%"
              :row-class-name="tableRowClassName"
              header-row-class-name="lus_table_head"
              @row-click="setIdx"
              class="lus_table"
            >
              <el-table-column
                prop="k2002"
                label="被测参数"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="k2110"
                label="LSL"
                align="center"
                width="50"
              ></el-table-column>
              <el-table-column
                prop="k2111"
                label="USL"
                align="center"
                width="50"
              ></el-table-column>
              <el-table-column
                prop="n"
                label="n（有效）"
                align="center"
                width="90"
              ></el-table-column>
              <el-table-column
                prop="avg"
                label="x̄"
                align="center"
                width="60"
              ></el-table-column>
              <el-table-column
                prop="sixSigma"
                label="99.73%"
                align="center"
                width="90"
              ></el-table-column>
              <el-table-column
                prop="cpTarget"
                label="CP目标"
                align="center"
                width="90"
              ></el-table-column>
              <el-table-column
                prop="cp"
                label="CP"
                align="center"
                width="50"
              ></el-table-column>
              <el-table-column
                prop="cpkTarget"
                align="center"
                label="CPK目标"
                width="90"
              ></el-table-column>
              <el-table-column
                prop="cpk"
                label="CPK"
                align="center"
                width="50"
              ></el-table-column>
              <el-table-column label="总体要求" align="center" width="100">
                <template slot-scope="scope">
                  <img
                    class="smile_icon"
                    src="@/assets/images/up_arraw.png"
                    alt=""
                    v-if="scope.row.status == 1"
                  />
                  <img
                    class="smile_icon"
                    src="@/assets/images/yellow_up_arraw.png"
                    alt=""
                    v-if="scope.row.status == 2"
                  />
                  <img
                    class="smile_icon"
                    src="@/assets/images/down_arraw.png"
                    alt=""
                    v-else-if="scope.row.status == 3"
                  />
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              style="margin-top: 5px; text-align: right"
              background
              layout="total, sizes,prev, pager, next"
              :total="total"
              :page-size="limit"
              :current-page.sync="page"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            >
            </el-pagination>
            <!-- <table class="lus_table">
              <tr>
                <th>被测参数</th>
                <th>LSL</th>
                <th>USL</th>
                <th>n（有效）</th>
                <th>x̄</th>
                <th>99.73%</th>
                <th>CP目标</th>
                <th>CP</th>
                <th>CPK目标</th>
                <th>CPK</th>
                <th>总体要求</th>
              </tr>
              <tr
                v-for="(item, idx) in lusTable"
                :key="idx"
                @click="setIdx(idx)"
              >
                <td>{{ item.k2002 }}</td>
                <td>{{ item.k2110 }}</td>
                <td>{{ item.k2111 }}</td>
                <td>{{ item.n }}</td>
                <td>{{ item.avg }}</td>
                <td>{{ item.sixSigma }}</td>
                <td>{{ item.cpTarget }}</td>
                <td>{{ item.cp }}</td>
                <td>{{ item.cpkTarget }}</td>
                <td>{{ item.cpk }}</td>
                <td>
                  <img
                    class="smile_icon"
                    src="@/assets/images/up_arraw.png"
                    alt=""
                    v-if="item.status == 1"
                  />
                  <img
                    class="smile_icon"
                    src="@/assets/images/yellow_up_arraw.png"
                    alt=""
                    v-if="item.status == 2"
                  />
                  <img
                    class="smile_icon"
                    src="@/assets/images/down_arraw.png"
                    alt=""
                    v-else-if="item.status == 3"
                  />
                </td>
              </tr>
            </table> -->
          </div>
        </el-col>
        <el-col :span="10">
          <div id="box_chart"></div>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <div id="line_chart"></div>
        </el-col>
      </el-row>
    </div>
    <div class="main" v-if="menuIdx == 1">
      <el-row :gutter="20">
        <el-col :span="24">
          <div id="line_chart"></div>
        </el-col>
      </el-row>
    </div>
    <div class="main" v-if="menuIdx == 2">
      <el-row :gutter="20">
        <el-col :span="24">
          <div id="box_chart"></div>
        </el-col>
      </el-row>
    </div>
  </detail-page>
</template>
<script>
import DetailPage from '../../components/DetailPage/index.vue'
import { getLusTable, getLusBox, getLusChart } from '@/api/lus'
import ecStat from 'echarts-stat'
export default {
  components: { DetailPage },
  data() {
    return {
      menuIdx: 0,
      chartIdx: 0,
      lusHeader: {
        k4092: '',
        k4093: '',
        k1000: '',
        k1002: '',
        k0008: '',
        beginTime: '',
        endTime: '',
        list: null,
      },
      addLineData: [],
      page: 1,
      limit: 20,
      total: 0,
      lusTable: [],
      lineList: [],
      boxList: [],
      nav_list: [
        {
          title: '产品状况+历史',
        },
        {
          title: '单值图',
        },
        {
          title: '箱型图',
        },
      ],
    }
  },
  created() {
    this.query = this.$route.query
  },
  mounted() {
    this.getLusTable()
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex
      return 'lus_table_td'
    },
    setIdx(row) {
      this.chartIdx = row.index
      this.getLusBox()
      this.getLusChart()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getLusTable()
    },
    handleSizeChange(val) {
      this.limit = val
      this.getLusTable()
    },

    async getLusTable() {
      let req_data = {
        k1000: this.query.k1000,
        k0010: this.query.k0010,
        startTime: this.query.startTime,
        endTime: this.query.endTime,
        page: this.page,
        limit: this.limit,
      }
      if (this.query.k0053) {
        req_data.k0053 = this.query.k0053
      }
      const { status, data } = await getLusTable(req_data)
      if (status == 200) {
        if (!data.lusHeaderModel) {
          this.$message.error('未查询到数据……')
          setTimeout(() => {
            // this.drawBarChart();
            window.history.go(-1)
          }, 2000)
          return
        }
        this.lusHeader = data.lusHeaderModel
        this.lusTable = data.resultPage.data
        this.total = data.resultPage.totalRow
        this.getLusBox()
        this.getLusChart()
      }
    },
    async getLusBox() {
      let list = []

      let idx = this.chartIdx
      let item = this.lusTable[idx]
      const { status, data } = await getLusBox({
        k0053: this.query.k0053,
        k1000: this.query.k1000,
        k0010: this.query.k0010,
        k2000: item?.k2000,
      })
      if (status == 200) {
        list.push(data[0])
        this.boxList = list
        this.drawBoxChart()
      }
    },
    changeMenu(idx) {
      this.menuIdx = idx
      switch (idx) {
        case '0':
          this.getLusTable()
          break
        case '1':
          this.getLusChart()
          break
        case '2':
          this.getLusBox()
          break
      }
    },
    // 绘制盒须图
    drawBoxChart() {
      this.$echarts.dispose(document.getElementById('box_chart'))
      let line_series = []
      let series = []
      let gap = 1
      let y_min = 0
      let y_max = 0
      let name = this.boxList[0].k2002
      this.boxList.map((item, idx) => {
        let value = { type: 'boxplot' }
        if (idx == 0) {
          let line_list = []

          let max_value = ecStat.statistics.max(item.values)
          let min_value = ecStat.statistics.min(item.values)

          let avg_value = ecStat.statistics.mean(item.values)

          if (item.up !== null) {
            line_list.push({
              yAxis: item.up,
              lineStyle: {
                color: 'red',
              },
            })
          }
          if (item.down !== null) {
            line_list.push({
              yAxis: item.down,
              lineStyle: {
                color: 'red',
              },
            })
          }
          line_list.push({
            name: '平均值',
            yAxis: avg_value,
            lineStyle: {
              color: 'rgb(92, 178, 52)',
            },
            label: {
              formatter: '{b}: {c}',
              color: 'rgb(92, 178, 52)',
            },
          })
          value.markLine = {
            data: line_list,
            symbol: 'none',
            silent: true,
          }

          value.markPoint = {
            data: [
              {
                name: '最大值',
                value: max_value,
                coord: [0, max_value],
                label: {
                  show: true,
                  position: 'right',
                  formatter: '{b}: {c}',
                },
              },
              {
                name: '最小值',
                value: min_value,
                coord: [0, min_value],
                label: {
                  show: true,
                  position: 'right',
                  formatter: '{b}: {c}',
                },
              },
            ],
            symbol: 'triangle',
            symbolSize: 10,
            itemStyle: {
              color: 'rgb(92, 178, 52)',
            },
          }
        }
        value.name = item.k2002
        value.data = [
          [item.min, item.q1, item.q2, item.q3, item.max, item.value],
        ]
        series.push(value)
        // values.push(item.values);

        // 绘制概率密度曲线
        let val = ecStat.histogram(item.values).data
        let start_item = val[0]
        let end_item = val[val.length - 1]
        gap = start_item[3] - start_item[2]
        val.unshift([start_item[0] - gap, 0])
        val.unshift([start_item[0] - 2 * gap, 0])
        val.push([end_item[0] + gap, 0])
        val.push([end_item[0] + 2 * gap, 0])
        y_max = end_item[0] + 3 * gap
        y_min = start_item[0] - 3 * gap
        let r_item = JSON.parse(JSON.stringify(val))
        val.map((vo, key) => {
          // val[key][1] = vo[1] - item.values.length * 0.5;
          r_item[key][1] = val[0][1] * 2 - val[key][1]
        })
        let line = {
          type: 'line',
          xAxisIndex: 1,
          showSymbol: false,
          smooth: true,
          encode: {
            x: 1,
            y: 0,
          },
          zlevel: 3,
          lineStyle: {
            color: '#3694ff',
            width: 1,
          },
        }
        // 绘制左侧曲线
        line.data = val
        line_series.push(line)
        // 绘制右侧曲线
        let re_line = JSON.parse(JSON.stringify(line))
        re_line.data = r_item
        line_series.push(re_line)
      })
      // let series = [
      //   {
      //     name: "boxplot",
      //     type: "boxplot",
      //     datasetIndex: 1,
      //   },
      //   {
      //     name: "outlier",
      //     type: "scatter",
      //     datasetIndex: 2,
      //   },
      // ];
      let option = {
        // legend: {
        //   right: 20,
        //   orient: "vertical",
        // },
        title: {
          left: 'center',
          text: name,
        },
        tooltip: {
          trigger: 'item',
          axisPointer: {
            type: 'shadow',
          },
        },
        grid: {
          left: '10%',
          top: '20%',
          right: '20%',
          bottom: '15%',
        },
        xAxis: [
          {
            type: 'category',
            show: false,
          },
          {
            type: 'value',
            show: false,
          },
        ],
        yAxis: {
          type: 'value',
          scale: true,
          splitArea: {
            show: false,
          },
          axisLine: {
            onZero: false,
          },
          min: y_min,
          max: y_max,
          minInterval: gap,
        },
        series: series,
      }
      let box_chart = this.$echarts.init(document.getElementById('box_chart'))
      box_chart.setOption(option)

      box_chart.on('mousemove', () => {
        let new_series = [...series, ...line_series]
        option.series = new_series
        box_chart.setOption(option)
      })
      box_chart.on('mouseout', () => {
        let new_series = [...series]
        option.series = new_series
        box_chart.setOption(option, true)
      })
    },
    // 获取折线图数据
    async getLusChart() {
      let list = []
      let idx = this.chartIdx
      let item = this.lusTable[idx]

      const { status, data } = await getLusChart({
        k0053: this.query.k0053,
        k1000: this.query.k1000,
        k0010: this.query.k0010,
        k2000: item?.k2000,
      })
      if (status == 200) {
        list.push(data)
        this.lineList = list
        setTimeout(() => {
          let item = this.lineList[0]
          let data = item.curveList
          this.addLineData = []
          for (let i = 0; i < data.length; i++) {
            this.addLineData.push('-')
          }
          this.drawLineChart()
        }, 200)
      }
    },
    drawLineChart() {
      let item = this.lineList[0]
      let data = item.curveList
      let name = item.list[0].k2002

      // 计算y轴的上下范围
      let values = item.list.map((vo) => {
        return vo.k0001
      })
      values.push(item.acceptanceDown)
      values.push(item.acceptanceUp)
      values.push(item.scrapDown)
      values.push(item.scrapUp)
      values.push(item.toleranceDown)
      values.push(item.toleranceUp)

      let max_value = ecStat.statistics.max(values)
      let min_value = ecStat.statistics.min(values)

      // 绘制标线
      let line_list = []
      // line_list.push({
      //   name:"中位数",
      //   type: 'median',
      //   lineStyle: { color: "(255, 137, 0)", type:'solid' },
      //   label:{
      //     formatter: '{b}: {c}',
      //     color: "(255, 137, 0)"
      //   }
      // })
      line_list.push({
        name: '平均数',
        type: 'average',
        lineStyle: { color: 'rgb(92, 178, 52)', type: 'solid' },
        label: {
          formatter: '{b}: {c}',
          color: 'rgb(92, 178, 52)',
        },
      })
      if (item.acceptanceDown !== null) {
        line_list.push({
          name: '控制限下限',
          yAxis: item.acceptanceDown,
          itemStyle: { color: 'rgb(92, 178, 52)' },
          label: {
            formatter: '{b}: {c}',
            color: 'rgb(92, 178, 52)',
          },
        })
        line_list.push({
          name: '控制限上限',
          yAxis: item.acceptanceUp,
          itemStyle: { color: 'rgb(92, 178, 52)' },
          label: {
            formatter: '{b}: {c}',
            color: 'rgb(92, 178, 52)',
          },
        })
      }
      if (item.toleranceUp !== null) {
        line_list.push({
          name: '公差限上限',
          yAxis: item.toleranceUp,
          itemStyle: { color: 'rgb(255, 137, 0)' },
          label: {
            formatter: '{b}: {c}',
            color: '(255, 137, 0)',
          },
        })
        line_list.push({
          name: '公差限下限',
          yAxis: item.toleranceDown,
          itemStyle: { color: 'rgb(255, 137, 0)' },
          label: {
            formatter: '{b}: {c}',
            color: '(255, 137, 0)',
          },
        })
      }
      if (item.scrapUp !== null) {
        line_list.push({
          name: '报废限上限',
          yAxis: item.scrapUp,
          itemStyle: { color: 'rgb(139, 0, 0)' },
          label: {
            formatter: '{b}: {c}',
            color: 'rgb(139, 0, 0)',
          },
        })
        line_list.push({
          name: '报废限下限',
          yAxis: item.scrapDown,
          itemStyle: { color: 'rgb(139, 0, 0)' },
          label: {
            formatter: '{b}: {c}',
            color: 'rgb(139, 0, 0)',
          },
        })
      }
      let addLineData = []
      addLineData = this.addLineData

      // let curveList = {};
      // let curveList = ecStat.regression("exponential", data);

      let chart = this.$echarts.init(document.getElementById('line_chart'))
      let option = {
        title: {
          left: 'center',
          text: name,
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line',
          },
          formatter: function(params) {
            let idx = params[0].dataIndex
            let info = item.list[idx]
            return '测量值：' + info.k0001 + '<br/>' + info.dateTime
          },
        },
        xAxis: { type: 'value', axisLine: { show: false } },
        yAxis: {
          type: 'value',
          axisLine: { show: false },
          // min: min_value - 1,
          // max: max_value + 1,
        },
        series: [
          {
            data: data,
            smooth: true,
            type: 'line',
            markLine: {
              symbol: ['none', 'none'],
              data: line_list,
            },
          },
          {
            data: addLineData,
            smooth: false,
            type: 'line',
            lineStyle: {
              type: 'dotted',
              color: '#5f5e5e',
            },
            markLine: {
              symbol: ['none', 'none'],
              data: line_list,
            },
          },
        ],
      }

      chart.setOption(option)
      chart.off('mouseout')
      chart.off('mousemove')

      let that = this
      chart.off('click')
      chart.on('click', function(params) {
        // let slice = addLineData.slice(params.dataIndex,1,params.data);
        that.addLineData[params.dataIndex] = params.data
        if (params.dataIndex != 0) {
          that.addLineData[params.dataIndex - 1] = data[params.dataIndex - 1]
        }
        if (params.dataIndex != data.length - 1) {
          that.addLineData[params.dataIndex + 1] = data[params.dataIndex + 1]
        }

        // let data = {
        //   x: params.name,
        //   y: params.value
        // }
        // clickTime(params.name)  //跳转函数
        data.splice(params.dataIndex, 1, '-')
        // that.$message.success(params.dataIndex)
        that.drawLineChart()
      })
      // this.chart_loading = false;
    },
  },
}
</script>

<style>
.el-table thead th {
  background-color: #d7d7d7 !important;
}
/* .lus_table_td:hover{
  background: slategrey !important;
} */
</style>
<style lang="scss" scoped>
.main {
  // max-height: 100%;
  // overflow-y: scroll;
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  // overflow: hidden;
  .el_row {
    flex: 1;
  }
}
.table_title {
  // margin-top: 100px;
  color: rgba(16, 16, 16, 100);
  font-size: 14px;
  text-align: center;
}
.table_sub {
  margin-top: 20px;
  flex: 1;
  // display: inline-block;
  // width: 50%;
  height: 48px;
  line-height: 48px;
  padding: 0 20px;
  // box-sizing: border-box;
  border-right: 1px solid #fff;
  background-color: rgba(54, 148, 255, 100);
  color: rgba(255, 255, 255, 100);
  font-size: 14px;
}

.lus_table {
  margin-top: 20px;
}
.smile_icon {
  width: 24px;
  height: 24px;
  display: block;
  margin: auto;
}

#box_chart {
  height: 500px;
}
#line_chart {
  min-height: 500px;
}
</style>
<style lang="scss">
.main_content[data-v-07047b33] {
  height: calc(100vh - 71px);
}
</style>
